var PaymentForm = function () {
  var AddPayModeForm = function () {
    var template = /* html */ `
      <div>
        <el-input v-model="payMode" size="small" style="width:100%" placeholder="请输入要添加的收付款方式"></el-input>
        <div style="text-align:center;margin-top:10px;">
          <el-button size="small" type="primary" @click="ensure">确定</el-button>
        </div>
      </div>
    `;

    return {
      props: {
        payModeList: {
          type: Array,
          default: function () {
            return [];
          }
        }
      },

      data: function () {
        return {
          payMode: ''
        };
      },

      methods: {
        ensure: function () {
          var payMode = this.payMode;
          if (payMode === '') {
            this.$alert('请输入付款方式', '信息');
            return;
          }

          var payModeList = this.payModeList;
          if (payModeList.indexOf(payMode) !== -1) {
            this.$alert('所添加的付款方式已存在，不能再添加', '信息');
            return;
          }
          this.$emit('add-mode', payMode);
          this.payMode = '';
        }
      },

      template: template
    };
  }();

  var template = /* html */ `
    <div class="payment-form" v-loading.fullscreen.lock="loading">
      <template v-if="paymentForm!==null">
        <el-form inline size="medium">
          <el-form-item required :label="type==='out'?'收款方式':'付款方式'">
            <el-select filterable v-model="paymentForm.receiptPaymentMode" class="form-input" :placeholder="type==='out'?'请选择收款方式':'请选择付款方式'">
              <el-option v-for="payMode in payModeList" :key="'payMode_'+payMode" :value="payMode">
              </el-option>
            </el-select>
            <el-popover v-model="showAddPayModeForm" trigger="click" width="200">
              <el-button slot="reference" type="primary">添加方式</el-button>
              <add-pay-mode-form :pay-mode-list="payModeList" @add-mode="addPayMode"></add-pay-mode-form>
            </el-popover>
          </el-form-item>
          <el-form-item label="折算金额">
            <el-input-number is-decimal-zero v-model="paymentForm.conversionPrice" class="form-input" :precision="4" :controls="false" :min="0"
              :max="sumPayPrice" placeholder="请输入折算金额"></el-input-number>
          </el-form-item>
          <el-form-item required label="银行卡号">
            <filter-select filterable v-model="paymentForm.relationBank" class="form-input" :options="bankCardList" value-field="num" label-field="num"
              placeholder="请选择银行卡号" :filter-method="cardFilterMehod">
              <template slot="item" slot-scope="scope">
                <div class="clearfix">
                  <span>{{scope.option.num}}</span>
                  <span style="float:right;color:#8492a6;margin-left:10px;font-size:12px">
                    {{scope.option.bankName}}
                  </span>
                </div>
              </template>
            </filter-select>
          </el-form-item>
          <el-form-item :label="type==='out'?'收款日期':'付款日期'">
            <el-date-picker v-model="paymentForm.actualDay" class="form-input" type="datetime" value-format="timestamp" :editable="false" :picker-options="actualDateOption"
              :placeholder="type==='out'?'请选择收款日期':'请选择付款日期'"></el-date-picker>
          </el-form-item>
          <el-form-item label="开票金额">
            <el-input-number is-decimal-zero v-model="paymentForm.invoicePrice" class="form-input" :min="0" :precision="4" :controls="false"
              placeholder="请输入开票金额"></el-input-number>
          </el-form-item>
          <el-form-item label="开票日期">
            <el-date-picker v-model="paymentForm.invoiceDate" class="form-input" value-format="timestamp" :editable="false" :picker-options="dateOption"
              placeholder="请选择开票日期"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="toPayment(1)">
              {{type==='out'?'收款':'付款'}}
            </el-button>
            <el-button type="primary" :disabled="!hasApproval" style="margin-left:0" @click="toPayment(2)">审核过账</el-button>
            <el-button type="primary" @click="toAdvancePayment">
              {{type==='out'?'预收款':'预付款'}}
            </el-button>
          </el-form-item>
        </el-form>
        <el-form inline size="medium">
          <el-form-item :label="type==='out'?'付款方':'收款方:'">
            <span>{{paymentForm.customerName}}</span>
          </el-form-item>
          <el-form-item :label="type==='out'?'总出库金额':'总入库金额:'">
            <span>{{sumTotalPrice}}</span>
          </el-form-item>
          <el-form-item :label="type==='out'?'总未收金额':'总未付金额:'">
            <span>{{sumNotPayPrice}}</span>
          </el-form-item>
          <el-form-item :label="type==='out'?'总收款金额':'总付款金额:'">
            <span>{{sumPayPrice}}</span>
          </el-form-item>
        </el-form>
        <div style="color:#ff0000">
          <span v-if="type==='out'">注：表格'已收'列，括号中为已收但未审核金额</span>
          <span v-else>注：表格'已付(未审)'列，括号中为已付但未审核金额</span>
        </div>
        <div>
          <el-table fit stripe border :data="paymentForm.warehouseList" style="width:100%">
            <slot name="table-column"></slot>

            <el-table-column :label="type==='out'?'已收(未审)':'已付(未审)'" key="payedPrice" min-width="120px" align="center">
              <template slot-scope="scope">
                <span>{{scope.row.payedPrice}} ({{scope.row.notApprovalPrice}})</span>
              </template>
            </el-table-column>
            <el-table-column :label="type==='out'?'未收':'未付'" prop="notPayPrice" key="notPayPrice" min-width="100px" align="center"></el-table-column>
            <el-table-column label="已审增减金额" prop="aleradyApprovalAddReducePrice" key="aleradyApprovalAddReducePrice" min-width="100px" align="center"></el-table-column>
            <el-table-column label="未审增减金额" prop="notApprovalAddReducePrice" key="notApprovalAddReducePrice" min-width="100px" align="center"></el-table-column>
            <el-table-column :resizable="false" :label="type==='out'?'收款金额':'付款金额'" key="payPrice" min-width="160px" header-align="center">
              <template slot-scope="scope">
                <el-input-number is-decimal-zero class="form-table-input" size="mini" v-model="scope.row.payPrice" :precision="4" :min="0" :controls="false"
                  :max="getMaxPayPrice(scope.row)"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column :resizable="false" label="增减类型" column-key="addReduceType" key="addReduceType" min-width="100px" header-align="center">
              <template slot-scope="scope">
                <el-select class="form-table-input" size="mini" v-model="scope.row.addReduceType" @change="addReduceTypeChange(scope.row)">
                  <el-option v-for="item in addReduceTypeList" :key="item.value" :value="item.value" :label="item.label"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column :resizable="false" label="增减金额" column-key="addReducePrice" key="addReducePrice" min-width="160px" header-align="center">
              <template slot-scope="scope" v-if="scope.row.addReduceType!==0">
                <el-input-number is-decimal-zero class="form-table-input" size="mini" v-model="scope.row.addReducePrice" :precision="4" :min="0" :controls="false"
                  :max="getMaxReducePrice(scope.row)"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column :resizable="false" label="增减原因" column-key="addReduceReason" key="addReduceReason" min-width="200px" header-align="center">
              <template slot-scope="scope" v-if="scope.row.addReduceType!==0">
                <el-input class="form-table-input" size="mini" v-model="scope.row.addReduceReason"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="margin:5px 0;">备注</div>
        <div>
          <el-input v-model="paymentForm.reason" style="width:100%" type="textarea" resize="none" :autosize="{minRows:3}" placeholder="请输入备注">
          </el-input>
        </div>
      </template>
      
      <el-dialog append-to-body fullscreen class="dialog-fullscreen" :title="type==='out'?'预收款':'预付款'" :visible.sync="openDialog">
        <div class="height:100%;overflow:auto">
          <advance-payment v-if="openDialog" :payment-form="paymentForm" :has-approval="hasApproval" :type="type" @pay-success="paySuccess"></advance-payment>
        </div>
      </el-dialog>
    </div>
  `;

  return {
    props: {
      warehouse: {
        type: [Object, Array],
        required: true
      },
      type: {
        type: String,
        default: 'material'
      }
    },

    computed: {
      sumTotalPrice: function () {
        var paymentForm = this.paymentForm;
        if (paymentForm === null) {
          return 0;
        }

        var warehouseList = paymentForm.warehouseList;
        var sumPrice = _.sumBy(warehouseList, 'totalPrice');
        return _.round(sumPrice, 4);
      },
      sumNotPayPrice: function () {
        var paymentForm = this.paymentForm;
        if (paymentForm === null) {
          return 0;
        }

        var warehouseList = paymentForm.warehouseList;
        var sumPrice = _.sumBy(warehouseList, 'notPayPrice');
        return _.round(sumPrice, 4);
      },
      sumPayPrice: function () {
        var paymentForm = this.paymentForm;
        if (paymentForm === null) {
          return 0;
        }

        return paymentForm.getSumPayPrice();
      }
    },

    data: function () {
      var self = this;
      return {
        loading: false,
        paymentForm: null,
        hasApproval: false,
        payModeList: [],
        showAddPayModeForm: false,
        bankCardList: [],
        addReduceTypeList: i18n.getDropDown('warehouseBalance.detail.addReduceType', [0, 1, 2]),
        dateOption: {
          disabledDate: function (time) {
            return !self.dateLimit(time);
          }
        },
        actualDateOption: {
          disabledDate: function (time) {
            return !self.dateLimit(time, 'second');
          }
        },
        openDialog: false
      };
    },

    created: function () {
      this.loading = true;
      var self = this;
      Promise.all([
        this.checkApproval(),
        this.setPayModeList(),
        this.setBankCardList(),
        this.setPayment()
      ]).then(function () {
        self.loading = false;
      }).catch(function () {
        self.loading = false;
      });
    },

    methods: {
      checkApproval: function () {
        var self = this;
        return PermissionUtil.ajaxCheckPermission(11).then(function (hasApproval) {
          self.hasApproval = hasApproval;
          return hasApproval;
        });
      },

      setPayModeList: function () {
        var self = this;
        return ajaxRequest('warehouseInSumMoney/getPaymentModeList').then(function (payModeList) {
          payModeList = _.filter(payModeList, function (payMode) {
            return !SysUtil.isEmpty(payMode) && payMode.trim() !== '';
          });
          payModeList = _.uniq(payModeList);
          self.payModeList = payModeList;
          return payModeList;
        });
      },

      setBankCardList: function () {
        var self = this;
        return ajaxRequest('finance/getAllBank').then(function (bankCardList) {
          bankCardList = _.map(bankCardList, function (card) {
            return {
              num: card.bankCardNumber,
              bankName: card.bank
            };
          });
          self.bankCardList = bankCardList;
          return bankCardList;
        });
      },

      cardFilterMehod: function (query, option) {
        if (query === '') {
          return true;
        }
        query = query.toLowerCase();

        var num = option.num;
        num = num.toLowerCase();
        var bankName = option.bankName;
        bankName = bankName.toLowerCase();
        return num.indexOf(query) !== -1 || bankName.indexOf(query) !== -1;
      },

      setPayment: function () {
        var warehouse = this.warehouse;
        var warehouses = null;
        if (_.isArray(warehouse)) {
          warehouses = warehouse;
        } else {
          warehouses = [warehouse];
        }

        var ids = _.map(warehouses, 'id');
        var self = this;
        return ajaxRequest('warehouseInSumMoney/getOneWarehousePayMentDetail', {
          idArray: JSON.stringify(ids)
        }).then(function (paymentList) {
          if (paymentList === null) {
            paymentList = [];
          }
          var paymentMap = {};
          for (var i = 0; i < paymentList.length; i++) {
            var payment = paymentList[i];
            var id = payment.inOutId;
            paymentMap[id] = payment;
          }

          var paymentForm = new PaymentModel(paymentMap, warehouses, self.type);
          self.paymentForm = paymentForm;
          return paymentForm;
        });
      },

      addPayMode: function (payMode) {
        this.payModeList.push(payMode);
        this.paymentForm.receiptPaymentMode = payMode;
        this.showAddPayModeForm = false;
      },

      addReduceTypeChange: function (warehouse) {
        warehouse.addReducePrice = undefined;
        var payPrice = warehouse.notPayPrice;
        if (warehouse.payPrice > payPrice) {
          warehouse.payPrice = payPrice;
        }
      },

      getMaxPayPrice: function (warehouse) {
        return this.paymentForm.getMaxPayPrice(warehouse);
      },

      getMaxReducePrice: function (warehouse) {
        return this.paymentForm.getMaxReducePrice(warehouse);
      },

      toPayment: function (payType) {
        var code = this.checkValid();
        if (code !== '') {
          var msg;
          if (this.type === 'out') {
            msg = i18n.getMsg(`outBalance.error.${code}`);
          } else {
            msg = i18n.getMsg(`warehouseBalance.error.${code}`);
          }
          this.$alert(msg, '信息');
          return;
        }

        var paymentForm = this.paymentForm;
        var postData = paymentForm.getObject(payType, this.type);
        this.loading = true;
        var self = this;
        ajaxRequest('warehouseInSumMoney/saveReceiptPaymentRecord', {
          jsonObject: JSON.stringify(postData)
        }).then(function () {
          var msg = '';
          if (self.type === 'out') {
            msg = payType === 1 ? '成功收款' : '成功收款并审核通过';
          } else {
            msg = payType === 1 ? '成功付款' : '成功付款并审核通过';
          }
          self.$alert(msg, '信息', {
            callback: function () {
              self.$emit('pay-success');
            }
          });
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },

      checkValid: function (isAdvance) {
        var paymentForm = this.paymentForm;
        var code = paymentForm.checkValid(isAdvance);
        if (code !== '') {
          return code;
        }

        var conversionPrice = paymentForm.conversionPrice;
        if (conversionPrice > this.sumPayPrice) {
          return 'conversionPrice>sumPayPrice';
        }
        return '';
      },

      dateLimit: function (time, type) {
        if (type === undefined) {
          type = 'day';
        }
        return moment(time).isSameOrBefore(moment(), type);
      },

      toAdvancePayment: function () {
        var code = this.checkValid(true);
        if (code !== '') {
          var msg;
          if (this.type === 'out') {
            msg = i18n.getMsg(`outBalance.error.${code}`);
          } else {
            msg = i18n.getMsg(`warehouseBalance.error.${code}`);
          }
          this.$alert(msg, '信息');
          return;
        }

        this.openDialog = true;
      },

      paySuccess: function () {
        this.openDialog = false;
        this.$emit('pay-success');
      }
    },

    components: {
      AddPayModeForm: AddPayModeForm,
      FilterSelect: FilterSelect,
      AdvancePayment: AdvancePayment
    },

    template: template
  };
}();
